
<template>
  <!-- 页面管理页面 -->
  <div class="editor_control_wrap">
    <div class="editor_control_wrap_main">
      <el-scrollbar style="height: 100%; width: 100%">
        <!-- 功能页面 -->
        <div class="tab_item" @click.prevent="fold('showUserList')">
          <i :class="
              showUserList ? 'el-icon-caret-bottom' : 'el-icon-caret-right'
            "></i>

          <span>功能页面</span>
        </div>
        <div v-if="showUserList" :class="`${showUserList}`">
          <div class="page_item" @click="selectPage('usercenter', '', 'usercenter', -1)">
            <span>用户中心</span>
            <span class="el-dropdown-link" v-if="functionpagetype === 'usercenter'">
              <i class="el-icon-edit-outline"></i>
            </span>
          </div>
        </div>
        <div class="page_item" @click="
            selectPage(
              'bussiness',
              livePage[0].components[0].link,
              livePage[0],
              -1,
            )
          ">
          <span>直播页面</span>
          <span class="el-dropdown-link" v-if="functionpagetype === 'bussiness'">
            <i class="el-icon-edit-outline"></i>
          </span>
        </div>
        <div>
          <!-- <div
            class="page_item"
            @click="
              selectcollagePage(
                'customize',
                '/pages/index/index?page=home',
                collageCategoryPage,
              )
            "
          >
            <span>拼团分类页</span>
            <span class="el-dropdown-link">
              <i class="el-icon-edit-outline"></i>
            </span>
          </div> -->
          <!-- <div class="page_item" v-for="item in functionPage" :key="item.id">
            <span class="page_name2">{{ item.name }}</span>
            <el-dropdown class="page_item_icon">
              <span class="el-dropdown-link">
                <i class="el-icon-more el-icon--right"></i>
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item>
                  <span @click="setLinkAddress(item.id)" class="block"
                    >页面路径</span
                  >
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </div> -->
        </div>
        <div>
          <!-- <div
            class="page_item"
            @click="
              selectcollagePage(
                'customize',
                '/pages/index/index?page=home',
                classificationPage,
              )
            "
          >
            <span>商超分类页</span>
            <span class="el-dropdown-link">
              <i class="el-icon-edit-outline"></i>
            </span>
          </div> -->
          <!-- <div class="page_item" v-for="item in functionPage" :key="item.id">
            <span class="page_name2">{{ item.name }}</span>
            <el-dropdown class="page_item_icon">
              <span class="el-dropdown-link">
                <i class="el-icon-more el-icon--right"></i>
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item>
                  <span @click="setLinkAddress(item.id)" class="block"
                    >页面路径</span
                  >
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </div> -->
        </div>

        <!-- 营销页面 -->
        <div class="tab_item" @click="fold('showBussinessList')">
          <i :class="
              showBussinessList ? 'el-icon-caret-bottom' : 'el-icon-caret-right'
            "></i>
          <span>商品专区</span>
        </div>

        <div v-if="showBussinessList">
          <div class="page_item" v-for="item in marketingPage" :key="item.id" @click="
              selectcollagePage(
                'customize',
                item.link,
                item.modeType === 'GROUP'
                  ? collageCategoryPage
                  : classificationPage,
                item,
                item.id,
              )
            ">
            <span class="page_name2">{{ item.modeName }}</span>
            <!-- <el-dropdown class="page_item_icon">
              <span class="el-dropdown-link">
                <i class="el-icon-more el-icon--right"></i>
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item>
                  <span>已是首页</span>
                </el-dropdown-item>
                <el-dropdown-item>
                  <span
                    @click="setLinkAddress(item.components[0].link)"
                    class="block"
                    >页面路径</span
                  >
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown> -->
            <span class="el-dropdown-link" v-if="activePageId && activePageId === item.id + ''">
              <i class="el-icon-edit-outline"></i>
            </span>
          </div>
        </div>

        <!-- 自定义页面 -->
        <div class="tab_item" @click="fold('showPageList')">
          <i :class="
              showPageList ? 'el-icon-caret-bottom' : 'el-icon-caret-right'
            "></i>

          <span>自定义页面</span>
        </div>

        <div v-if="showPageList">
          <div v-for="item in pageList" :key="item.id" class="page_item" @click="
              selectPage(
                'customize',
                '/subcontract/pages/index/index?page=home',
                item,
                -1,
              )
            ">
            <GoodNameEdit :good-name="item.pageName" :good="item" @change="updateGoodName" />
            <div style="font-size: 12px; color: #9999" v-if="item.isDef !== '0'">
              首页
            </div>
            <el-dropdown class="page_item_icon">
              <span class="el-dropdown-link">
                <i class="el-icon-more el-icon--right"></i>
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item>
                  <span @click="setHomePage(item, item.pageName)" v-if="item.isDef === '0'">设为首页</span>
                </el-dropdown-item>
                <el-dropdown-item v-if="item.isDef === '0'">
                  <span @click="delPage(item.id)" class="block">删除</span>
                </el-dropdown-item>
                <el-dropdown-item v-if="item.isDef !== '0'">
                  <span @click="
                      setLinkAddress('/subcontract/pages/index/index?page=home')
                    " class="block">页面路径</span>
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </div>
        </div>

        <div class="add_page_btn" @click="addPage()" v-if="pageList.length < 10">
          <span>+ 添加页面</span>
        </div>
      </el-scrollbar>
    </div>
  </div>
</template>

<script lang="ts">
import { Vue, Component, Prop, Watch, Emit } from "vue-property-decorator";
import EdtiorFormData from "./compontents/index/formModel";
import { CustomizedPages, CategoryPage } from "./interfaces/EditorControlPage";
import {
  addAssembly,
  getPageList,
  delPage,
  addPage,
  getJudgeAssembly,
} from "@/api/group/group";
import GoodNameEdit from "@/components/GoodNameEdit2.vue"; // 编辑商品名称
import UserCenterDialog from "./compontents/userCenterDialog/userCenterDialog.vue";
import { getControl, addControl } from "@/api/decoration/decoration";
// import SpellGroup from "./compontents/SpellGroup/SpellGroup";
import { IComponentItem, IComponent } from "./interfaces/component";
import { getAllRegionList } from "@/api/good/goods";

@Component({
  components: { GoodNameEdit, UserCenterDialog },
})
export default class DecorationComponent extends Vue {
  @Prop()
  templateId;

  @Prop()
  activePageId;

  /** 当前自定义页面 */
  currentItem: any = {};

  /** 更换模板弹窗 */
  dialogShow = false;

  /** 判断更改标题新增 */
  activeType = 0;

  /** 展示用户中心列表 */
  showUserList = true;

  /** 展示营销列表 */
  showBussinessList = true;

  /** 展示自定义列表 */
  showPageList = true;

  /** 自定义页面列表 */
  pageList: CustomizedPages[] = [
    {
      id: 1,
      name: "空白页",
      isHome: false,
    },
  ];

  /** 拼团分类页 */
  collageCategoryPage: CategoryPage = {
    id: 1,
    name: "拼团分类页",
    isHome: false,
    type: "1",
  };

  /** 商超分类页 */
  classificationPage: CategoryPage = {
    id: 0,
    name: "商超分类页",
    isHome: false,
    type: "2",
  };

  /** 首页页面id匹配首页 */
  homeId: number | string = "";

  /** 获取的首页tab配置，设置时写回去 */
  homePlugin: any = {};

  /** 功能页面 */
  functionPage: any[] = [];

  livePage: any[] = [
    {
      name: "直播页面",
      components: [
        {
          formData: {},
          icon: "",
          label: "直播",
          value: "Live",
          link: "/subcontract/pages/live/live",
        },
      ],
    },
  ];

  /** 营销页面 */
  marketingPage: any[] = [
    {
      name: "直播页面",
      components: [
        {
          formData: {},
          icon: "",
          label: "直播",
          value: "Live",
          link: "/subcontract/pages/live/live",
        },
      ],
    },
  ];

  /** 功能页面选中 */
  // functionpage: string = "";
  get functionpagetype() {
    return this.$store.state.decoration.activePageType;
  }

  /** 商品专区页面选中 */
  // get activePageid() {
  //   return this.$store.state.decoration.activePage.modelId;
  // }
  // activePageid: any = ''
  // @Watch('activePage', { deep: true })
  // setactivePage(){
  //   this.activePage = this.$store.state.decoration.activePage
  // }

  async getMarketingPage() {
    const res = await getAllRegionList({});
    const data = res.data;
    data.forEach((item) => {
      item.link = "/pages/index/index?page=home";
    });
    this.marketingPage = data;
    // this.getPageList();
  }

  /** 设为首页 */
  async setHomePage(item) {
    await this.getControlList();
    this.addOrEditControl(item.id);
    await this.editOrAdd({ id: item.id, isDef: 1 }, 3);
    this.getPageList();
  }

  /**
   * 初始获取控件数据
   */
  async getControlList() {
    const res = await getControl({
      templateId: this.$store.state.decoration.templateId,
      pluginNameEn: "navBar",
      isDeleted: 0,
    });
    try {
      if (res.code === 200 && res.data.length > 0) {
        this.homePlugin = res.data[0];
        const navBarPlugin = JSON.parse(res.data[0].pluginProperties)[0]
          .formData.menuList;
        if (navBarPlugin && navBarPlugin.length > 0) {
          const navbarHome = navBarPlugin.filter((item) => item.isHome);
          const { linkUrl, type, id } = navbarHome[0].linkUrl;
          if (type === 5 && linkUrl === "pages/index/index") {
            this.homeId = id;
          }
        }
      }
    } catch (error) {
      this.$message.warning(`${error}获取数据失败`);
    }
  }

  /**
   * 修改/新增控件
   */
  async addOrEditControl(id) {
    const { homePlugin } = this;
    let pluginProperties = JSON.parse(homePlugin.pluginProperties)[0];
    let formData = JSON.parse(homePlugin.pluginProperties)[0].formData;
    const navBarPlugin = JSON.parse(homePlugin.pluginProperties)[0].formData
      .menuList;
    this.dealEditControl({ navBarPlugin, id });
    formData = { ...formData, menuList: navBarPlugin };
    pluginProperties = [{ ...pluginProperties, formData }];
    homePlugin.pluginProperties = JSON.stringify(pluginProperties);
    const res = await addControl(homePlugin);
    try {
      if (res.code === 200) {
        this.$message.success("设置首页成功");
      } else {
        this.$message.warning("设置失败");
      }
    } catch (error) {
      this.$message.warning(`${error}获取数据失败`);
    }
  }

  /**
   * 处理控件数据
   */
  dealEditControl({ navBarPlugin, id }) {
    navBarPlugin.map((item, i) => {
      if (item.isHome) {
        navBarPlugin[i].id = id;
        navBarPlugin[i].linkUrl = "pages/index/index";
        navBarPlugin[i].type = 5;
        navBarPlugin[i].linkName = name;
        return {
          ...navBarPlugin,
        };
      }
    });
  }

  /**
   * 展示用户中心
   */
  showUserCenter() {
    this.dialogShow = true;
  }

  /**
   * 初始获取自定义页面数据
   */
  created() {
    this.getMarketingPage();
    this.getPageList();
    this.getControlList();
  }

  /**
   * 获取自定义页面数据
   */
  @Watch("templateId")
  async getPageList() {
    const res = await getPageList({ templateId: this.templateId, size: 100 });
    try {
      if (res.code === 200) {
        const list = res.data.list || [];
        this.pageList = this.filterFunctionPage(list);
        if (
          !this.$store.state.decoration.firstStatus &&
          !this.$store.state.decoration.isUsercenterCompontents &&
          this.activeType !== 1 &&
          res.data.list.length
        ) {
          const activePage = res.data.list.filter(
            (item) => item.isDef !== "0",
          )[0];
          // 初始化获取 设为首页的页面id
          const homePageId = res.data.list.filter(
            (item) => item.isDef !== "0",
          )[0].id;
          this.$store.commit("decoration/SET_HOME_PAGE_ID", homePageId);
          this.$store.commit("decoration/SET_ACTIVEPAGE", activePage); // 初始化 首页列表
          this.$store.commit("decoration/SET_FIRSTSTATUS", true); // 初始化用户是不是第一次编辑
        }
      } else {
        this.$message.warning(`获取数据失败，请稍后重试`);
      }
    } catch (e) {
      this.$message.warning(`获取数据失败，请稍后重试`);
    }
  }

  /**
   * 过滤功能页面
   * 因为现在的功能页是存在自定义页面的
   */
  filterFunctionPage(list) {
    const temp1 = list.find((i) => i.type === "1");
    const temp2 = list.find((i) => i.type === "2");
    if (temp1) this.collageCategoryPage = temp1;
    if (temp2) this.classificationPage = temp2;
    return list.filter((i) => i.type !== "1" && i.type !== "2");
  }

  /**
   * 修改/新增自定义页面
   */
  async editOrAdd(data, type) {
    const res = await addPage(data);
    try {
      if (res.code === 200) {
        this.activeType = 1;
        if ([1, 2].includes(type))
          this.$message.success(`${type === 1 ? "新增" : "修改"}页面成功`);
        if (type === 1)
          this.$store.commit("decoration/SET_ACTIVEPAGE", res.data);
        this.getPageList();
      }
    } catch (e) {
      this.$message.warning(`编辑自定义页面失败，请稍后重试`);
    }
  }

  /**
   * 折叠标签
   */
  fold(v) {
    this[`${v}`] = !this[`${v}`];
  }

  /**
   * 新增自定义页面
   */
  addPage() {
    let data = {
      isDef: 0,
      pageName: "自定义页面",
      templateId: this.templateId,
    };
    if (!this.pageList.length) {
      data = {
        isDef: 1,
        pageName: "首页",
        templateId: this.templateId,
      };
    }
    this.editOrAdd(data, 1);
  }

  /**
   * 删除页面
   */
  async delPage(id) {
    const res = await delPage({ ids: id });
    try {
      if (res.code === 200) {
        this.$message.success(`操作成功`);
        this.activeType = 0;
        this.$store.commit("decoration/SET_FIRSTSTATUS", false);
        this.getPageList();
      } else {
        this.$message.warning(`删除自定义页面失败，请稍后重试！`);
      }
    } catch (e) {
      this.$message.warning(`删除自定义页面失败，请稍后重试！`);
    }
  }

  /**
   * 点击自定义页面装修
   */
  async selectPage(type, link, item) {
    this.currentItem = item;
    const c = this.$parent.components || [];
    // 如果是分类页需要检测是否输入完成
    if (
      (["1", "2"].includes(item.type) ||
        (c.length && ["BusinessSuper", "SpellPage"].includes(c[0].value))) &&
      c.length &&
      !this.$parent.checkClassPage(c[0], { chanel: "pageTab" })
    ) {
      return false;
    }
    this.$store.commit("decoration/SET_ACTIVEPAGETYPE", { type, link });
    this.$store.commit("decoration/SET_ACTIVEPAGE", item);
  }

  /**
   * 初始化请求参数
   */
  initPostData({ type }) {
    const tempdata = { icon: "", value: "SpellPage", label: "拼团分类页" };
    if (type === "2") {
      tempdata.value = "BusinessSuper";
      tempdata.label = "商超分类页";
    }
    return { ...tempdata };
  }

  /**
   * 选择拼团/商超分类页
   */
  async selectcollagePage(type, link, item, newItem: any = {}) {
    // test tip
    if (newItem.id) {
      item.modelId = newItem.id;
    }
    const param = {
      modelId: newItem.id,
    };
    if (newItem.link) {
      getJudgeAssembly(param).then(async (res) => {
        // return;
        if (res.data.length === 0) {
          const data = {
            isDef: 0,
            pageName: item.name,
            templateId: this.templateId,
            type: item.type,
            modelId: newItem.id,
          };
          const res = (await addPage(data)) as any;
          if (res.code !== 200) return this.$message.error(res.msg);
          const tempdata = {
            icon: "",
            value: "SpellPage",
            label: "拼团分类页",
          } as any;
          if (item.type === "2") {
            tempdata.value = "BusinessSuper";
            tempdata.label = "商超分类页";
          }
          const com = this.getNewComponent(tempdata) as any;
          const addmsg = await this.addNewComponent(com, {
            pageId: res.data.id,
            templateId: res.data.templateId,
          });
          if (addmsg.code !== 200) return this.$message.error(addmsg.msg);
          if (item.type === "1") {
            this.collageCategoryPage = res.data;
          } else if (item.type === "2") {
            this.classificationPage = res.data;
          }
          this.handleAddComponent(tempdata);
          this.$store.commit("decoration/SET_ACTIVEPAGE", res.data);
          this.selectPage(type, link, res.data);
        } else {
          this.$store.commit("decoration/SET_ACTIVEPAGE", item);
          this.selectPage(type, link, item);
        }
      });
    }
    // if (!item.id) {
    //   const data = {
    //     isDef: 0,
    //     pageName: item.name,
    //     templateId: this.templateId,
    //     type: item.type,
    //   };
    //   const res = (await addPage(data)) as any;
    //   if (res.code !== 200) return this.$message.error(res.msg);
    //   const tempdata = { icon: "", value: "SpellPage", label: "拼团分类页" };
    //   if (item.type === "2") {
    //     tempdata.value = "BusinessSuper";
    //     tempdata.label = "商超分类页";
    //   }
    //   const com = this.getNewComponent(tempdata) as any;
    //   const addmsg = await this.addNewComponent(com, {
    //     pageId: res.data.id,
    //     templateId: res.data.templateId,
    //   });
    //   if (addmsg.code !== 200) return this.$message.error(addmsg.msg);
    //   if (item.type === "1") {
    //     this.collageCategoryPage = res.data;
    //   } else if (item.type === "2") {
    //     this.classificationPage = res.data;
    //   }
    //   this.handleAddComponent(tempdata);
    //   this.$store.commit("decoration/SET_ACTIVEPAGE", res.data);
    //   this.selectPage(type, link, res.data);
    // } else {
    //   this.selectPage(type, link, item);
    // }
  }

  /**
   * 默认推入一个
   */
  @Emit("change")
  handleAddComponent(currentComponent: IComponentItem): IComponent {
    currentComponent.type = true; // 专区分类页跳过限制添加组件提示
    return this.getNewComponent(currentComponent);
  }

  /**
   * 返回一个新页面对象
   */
  getNewComponent(currentComponent: IComponentItem): IComponent {
    const FormData = EdtiorFormData[currentComponent.value];
    return { ...currentComponent, id: Date.now(), formData: new FormData() };
  }

  /**
   * 手动指定插入一个组件到一个页面
   */
  async addNewComponent(data, option) {
    const properties = JSON.stringify({ ...data });
    const assembly = {
      properties,
      ...option,
    };
    const res = await addAssembly([assembly]);
    return res;
  }

  /**
   * 修改自定义页面名称
   */
  updateGoodName(newName: string) {
    let name = newName;
    if (newName.length > 15) {
      this.$message.warning("自定义页面名称最大15个字符！");
      name = newName.substring(0, 15);
    }
    const param = {
      id: this.currentItem.id,
      pageName: name,
    };
    this.editOrAdd(param, 2);
  }

  /**
   * 设置分享链接
   */
  setLinkAddress(link) {
    this.$emit("change");
    this.$store.commit("decoration/SET_ACTIVEPAGETYPE", { link });
  }
}
</script>
<style lang="scss" scoped>
@import "@/assets/styles/decoration/editorControlPage";
.page_item_icon {
  height: 12px;
  margin-bottom: 23px;
}
</style>
